import Taro from '@tarojs/taro'
import qs from 'kuan-utils/lib/qs'
import authority from '../authority'
import { toast as showErr } from '../feedBack'
import encrypt from './encrypt.js' // 加密对接
import constants from '@/constants' // 配置文件

export default ({
  baseUrl = constants.apiUrl,
  url,
  data = {},
  params = {},
  method = 'get',
  header: defaultHeader = {}
}) => {
  const now = ~~(new Date().getTime() / 1000)
  const { token, city = {}, visitor = {} } = authority.get() || {}
  const { shop_id, region_code } = city
  const header = {
    'content-type': 'application/json',
    'X-Halo-App': constants.haloApp,
    'X-Halo-Region': region_code || 320500,
    'Http-Request-Halo-Time': now,
    'X-Halo-Source': constants.haloApp,
    'Http-Request-Halo-Sign': encrypt({ ...params, ...data, time: now }),
    'X-Halo-Visitor': visitor.visitor_id || '',
    'X-Shop-Id': shop_id,
    ...defaultHeader
  }

  if (token) header.Authorization = `Bearer ${token}`

  return new Promise(async (resolve, reject) => {
    let search = qs.stringify(params)
    const finalUrl = url.startsWith('http') ? url : `${baseUrl}${url}`
    const options = {
      url: finalUrl + (search ? `?${search}` : search),
      data,
      method: method.toUpperCase(),
      header
    }
    Taro.request({
      ...options,
      success(result) {
        const { iRet, data, info } = result.data
        if (iRet !== 1) {
          if (result.statusCode !== 401) showErr(info)
          reject(result)
        } else {
          resolve(data)
        }
      },
      fail(e) {
        showErr('网路异常')
        reject(e)
      }
    })
  })
}
